using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Project.EPMSync.Config.Library;
using System.Data.SqlClient;
using System.Net;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Web.Services.Protocols;
using System.Collections.ObjectModel;
using Microsoft.Office.Project.EPMSync.Config.Editor.Properties;
using System.Globalization;

namespace Microsoft.Office.Project.EPMSync.Config.Editor
{

    public partial class FormEditFieldMappings : Form
    {
        private Dictionary<Guid, string> _customFieldList;
        private Dictionary<int, string> _attributeList;
        private Dictionary<int, FieldMapping> _fieldMappings;

        private Dictionary<int, AttributeDefinitionList> _attributeDefList;
        private Dictionary<Guid, LookupTableDefinitionList> _lookupTableDefList;
        private Dictionary<Guid, Guid> _customFieldsWithLookupTables;

        FormMain ptrMain;

        public FormEditFieldMappings(FormMain main)
        {
            InitializeComponent();
            ptrMain = main;
        }

        #region External Methods

        public void UpdateLookupValues(int attributeId, Dictionary<int, Guid> lookupValues)
        {
            if (_fieldMappings[attributeId].LookupMap == null)
                _fieldMappings[attributeId].LookupMap = new Collection<LookupMapEntry>();
            else
                _fieldMappings[attributeId].LookupMap.Clear();

            foreach (KeyValuePair<int, Guid> kvp in lookupValues)
            {
                _fieldMappings[attributeId].LookupMap.Add(new LookupMapEntry(kvp.Key, kvp.Value));
            }
        }

        #endregion

        #region Create Lists

        public bool SetLists(string serverUrl, string ppsDBConnectionString, string accountId, Collection<FieldMapping> fieldMappings)
        {

            if (ReadCustomFieldList(serverUrl) &&
                ReadAttibuteList(accountId, ppsDBConnectionString) &&
                ReadAttibuteDefinitionList(accountId, ppsDBConnectionString) &&
                ReadLookupTableList(serverUrl))
            {
                foreach (string attributeName in _attributeList.Values)
                {
                    listBoxAvailablePPSFields.Items.Add(attributeName);
                }

                _fieldMappings = new Dictionary<int, FieldMapping>();
                foreach (FieldMapping fm in fieldMappings)
                {
                    AddToMappingList(fm.PPSAttributeId);
                    _fieldMappings.Add(fm.PPSAttributeId, fm);
                }

                // Read the built in field list
                comboBoxPSBuiltInField.Items.Add(String.Empty);
                foreach (string fieldName in BuiltInFields.FieldNames)
                {
                    comboBoxPSBuiltInField.Items.Add(fieldName);
                }

                // Populate the custom field list
                comboBoxPSCustomField.Items.Add(String.Empty);
                foreach (string customFieldName in _customFieldList.Values)
                {
                    comboBoxPSCustomField.Items.Add(customFieldName);
                }

                // Disable the drop downs and radio buttons till there is a selection in listBoxMappedPPSFields
                ChangePSMappingControlsEnabled(false);

                return true;
            }
            else
            {
                RightAwareMessageBox.Show(Resources.EmptyAttributeList, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return false;
            }
        }

        private bool ReadAttibuteList(string accountId, string ppsDBConnectionString)
        {
            _attributeList = new Dictionary<int, string>();
            bool successful = true;

            try
            {
                //SELECT att.ID, att.Name,  attcat.Name
                //FROM sfATTRIBUTES AS att
                //LEFT JOIN sfATTRIBUTE_CATEGORIES AS attcat
                //ON att.CategoryID = attcat.ID
                //WHERE (att.AccountID = 104) AND (att.EntityType = 'PROJECT') 
                //ORDER BY att.Name
                string queryString = String.Format(CultureInfo.InvariantCulture, "SELECT att.ID, att.Name,  attcat.Name FROM sfATTRIBUTES AS att LEFT JOIN sfATTRIBUTE_CATEGORIES AS attcat ON att.CategoryID = attcat.ID WHERE (att.AccountID = {0}) AND (att.EntityType = 'PROJECT') ORDER BY att.Name", accountId);

                using (SqlConnection connection = new SqlConnection(ppsDBConnectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        _attributeList.Add((int)reader[0], EnhancedAttributeName(reader[1], reader[2]));
                    }

                    reader.Close();
                }

            }
            catch (Exception ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ExceptionString, ex.Message), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                successful = false;
            }

            return successful;
        }

        private bool ReadAttibuteDefinitionList(string accountId, string ppsDBConnectionString)
        {
            _attributeDefList = new Dictionary<int, AttributeDefinitionList>();
            bool successful = true;

            try
            {
                string queryString = "SELECT ID, AttributeID, _Value FROM sfATTRIBUTE_DEFINITIONS ORDER BY _Value ASC";

                using (SqlConnection connection = new SqlConnection(ppsDBConnectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        _attributeDefList.Add((int)reader[0], new AttributeDefinitionList((int)reader[0], (int)reader[1], reader[2].ToString()));
                    }

                    reader.Close();

                    // Get the AttributeID for WORKFLOW_STATUS
                    queryString = String.Format(CultureInfo.InvariantCulture, "SELECT ID FROM sfATTRIBUTES WHERE AccountID = {0} AND InternalName='WORKFLOW_STATUS'", accountId);
                    command = new SqlCommand(queryString, connection);
                    int WFAttributeID = (int)command.ExecuteScalar();

                    //SELECT     items.ID, dia.Name, gates.Name, items.Name
                    //FROM         wfITEMS items
                    //inner join wfGATES as gates
                    //ON items.GateID = gates.ID
                    //INNER JOIN wfDIAGRAM dia
                    //ON items.DiagramID = dia.ID
                    //WHERE     (gates.AccountID = 104)
                    //ORDER BY dia.Name, gates.Name, items.Name ASC
                    // Get the workflow specific items
                    queryString = String.Format(CultureInfo.InvariantCulture, "SELECT items.ID, diagram.Name, gates.Name, items.Name FROM wfITEMS items INNER JOIN wfGATES as gates ON items.GateID = gates.ID INNER JOIN wfDIAGRAM diagram ON items.DiagramID = diagram.ID WHERE (gates.AccountID = {0}) ORDER BY diagram.Name, gates.Name, items.Name ASC", accountId.ToString());
                    //queryString = "SELECT ID, Name FROM wfITEMS";
                    command = new SqlCommand(queryString, connection);

                    reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        //Console.WriteLine(String.Format("ItemID: {0}, AttributeID: {1}, ItemName: {2}", (int)reader[0], String.Format("{0}.{1}.{2}", reader[1], reader[2], reader[3])));
                        _attributeDefList.Add((int)reader[0], new AttributeDefinitionList((int)reader[0], (int)WFAttributeID, String.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}", reader[1], reader[2], reader[3])));
                    }


                }

            }
            catch (Exception ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ExceptionString, ex.Message), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                successful = false;
            }

            return successful;
        }

        private static string EnhancedAttributeName(object attributeName, object attributeCategory)
        {
            if (attributeCategory.GetType() == typeof(System.DBNull))
                return attributeName.ToString();
            else
                return String.Format(CultureInfo.InvariantCulture, "{0} - {1}", attributeName.ToString(), attributeCategory.ToString());
        }

        private bool ReadCustomFieldList(string serverUrl)
        {
            CustomFieldsWS.CustomFields customFieldsWebSvc = new CustomFieldsWS.CustomFields();
            customFieldsWebSvc.CookieContainer = new CookieContainer();
            customFieldsWebSvc.Credentials = CredentialCache.DefaultCredentials;
            customFieldsWebSvc.Url = WebServiceUrl.CustomFields(serverUrl);

            _customFieldList = new Dictionary<Guid, string>();
            _customFieldsWithLookupTables = new Dictionary<Guid, Guid>();
            try
            {
                CustomFieldsWS.CustomFieldDataSet cfDataSet = customFieldsWebSvc.ReadCustomFieldsByEntity(new Guid(PSLibrary.EntityCollection.Entities.ProjectEntity.UniqueId));

                foreach (CustomFieldsWS.CustomFieldDataSet.CustomFieldsRow cfr in cfDataSet.CustomFields)
                {
                    _customFieldList.Add(cfr.MD_PROP_UID, cfr.MD_PROP_NAME);
                    if (!cfr.IsMD_LOOKUP_TABLE_UIDNull())
                        _customFieldsWithLookupTables.Add(cfr.MD_PROP_UID, cfr.MD_LOOKUP_TABLE_UID);
                }

            }
            catch (Exception ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ExceptionString, ex.Message), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;

        }

        private static string SortedLookupTableTreeFilter
        {
            get
            {
                LookupTableWS.LookupTableDataSet ltds = new LookupTableWS.LookupTableDataSet();

                string tableName = ltds.LookupTableTrees.TableName;
                string nameColumn = ltds.LookupTableTrees.LT_VALUE_FULLColumn.ColumnName;
                string uidColumn = ltds.LookupTableTrees.LT_UIDColumn.ColumnName;
                string structUidColumnName = ltds.LookupTableTrees.LT_STRUCT_UIDColumn.ColumnName;

                PSLibrary.Filter.FieldOperationType notEqual = PSLibrary.Filter.FieldOperationType.NotEqual;
                //PSLibrary.Filter.SortOrderTypeEnum sortOrder = PSLibrary.Filter.SortOrderTypeEnum.Asc;

                PSLibrary.Filter cfFilter = new PSLibrary.Filter();
                cfFilter.FilterTableName = tableName;
                cfFilter.Fields.Add(new PSLibrary.Filter.Field(tableName, nameColumn));
                //cfFilter.Fields.Add(new PSLibrary.Filter.Field(tableName, nameColumn, sortOrder)); // This fails :(
                cfFilter.Fields.Add(new PSLibrary.Filter.Field(uidColumn));
                cfFilter.Fields.Add(new PSLibrary.Filter.Field(structUidColumnName));

                cfFilter.Criteria = new PSLibrary.Filter.FieldOperator(notEqual, uidColumn, Guid.Empty);

                return cfFilter.GetXml();
            }
        }

        private bool ReadLookupTableList(string serverUrl)
        {
            LookupTableWS.LookupTable _lookupTableWebSvc = new LookupTableWS.LookupTable();
            _lookupTableWebSvc.CookieContainer = new CookieContainer();
            _lookupTableWebSvc.Credentials = CredentialCache.DefaultCredentials;
            _lookupTableWebSvc.Url = WebServiceUrl.LookupTable(serverUrl);

            _lookupTableDefList = new Dictionary<Guid, LookupTableDefinitionList>();
            try
            {
                //LookupTableWS.LookupTableDataSet ltds = _lookupTableWebSvc.ReadLookupTables(SortedLookupTableTreeFilter, false, 0);
                LookupTableWS.LookupTableDataSet ltds = _lookupTableWebSvc.ReadLookupTables("", false, 0);
                foreach (LookupTableWS.LookupTableDataSet.LookupTableTreesRow lttr in ltds.LookupTableTrees)
                {
                    _lookupTableDefList.Add(lttr.LT_STRUCT_UID, new LookupTableDefinitionList(lttr.LT_UID, lttr.LT_STRUCT_UID, lttr.LT_VALUE_FULL));
                }

            }
            catch (SoapException ex)
            {
                string errMess = "";
                // Pass the exception to the PSClientError constructor to 
                // get all error information.
                PSLibrary.PSClientError psiError = new PSLibrary.PSClientError(ex);
                PSLibrary.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                for (int j = 0; j < psiErrors.Length; j++)
                {
                    errMess += psiErrors[j].ErrId.ToString() + "\n";
                }
                errMess += "\n" + ex.Message.ToString();
                // Send error string to console or message box.

                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ExceptionString, errMess), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (Exception ex)
            {
                RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ExceptionString, ex.Message), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;

        }

        //private static string SetCustomFiedldsURL(string serverInstance)
        //{
        //    if (!serverInstance.EndsWith("/"))
        //        serverInstance += "/";
        //    return serverInstance + "_vti_bin/psi/customfields.asmx";
        //}

        //private static string SetLookupTableURL(string serverInstance)
        //{
        //    if (!serverInstance.EndsWith("/"))
        //        serverInstance += "/";
        //    return serverInstance + "_vti_bin/psi/lookuptable.asmx";
        //}


        #endregion

        #region List Utility Methods

        private void AddToMappingList(int attributeId)
        {
            listBoxAvailablePPSFields.Items.Remove(_attributeList[attributeId]);
            listBoxMappedPPSFields.Items.Add(_attributeList[attributeId]);
        }

        private void RemoveFromMappingList(int attributeId)
        {
            listBoxAvailablePPSFields.Items.Add(_attributeList[attributeId]);
            listBoxMappedPPSFields.Items.Remove(_attributeList[attributeId]);
        }

        private int getAttributeID(string attributeName)
        {
            foreach (KeyValuePair<int, string> kvp in _attributeList)
            {
                if (kvp.Value == attributeName)
                {
                    return kvp.Key;
                }
            }

            // A valid attribute was not found in the list
            return 0;

        }

        private Guid getCustomFieldGuid(string customFieldName)
        {
            foreach (KeyValuePair<Guid, string> kvp in _customFieldList)
            {
                if (kvp.Value == customFieldName)
                {
                    return kvp.Key;
                }
            }

            // A valid attribute was not found in the list
            return Guid.Empty;

        }
        #endregion

        #region Lookup Table Definition Utility Methods
        private Collection<LookupMapEntry> GetLookupMapTable(int attributeId)
        {
            return _fieldMappings[attributeId].LookupMap;
        }

        private Dictionary<int, string> GetAttributeDefinitionList(int attributeId)
        {
            Dictionary<int, string> adl = new Dictionary<int, string>();
            foreach (KeyValuePair<int, AttributeDefinitionList> kvp in _attributeDefList)
            {
                if (kvp.Value.AttributeId == attributeId)
                {
                    adl.Add(kvp.Value.Id, kvp.Value.Value);
                }
            }
            return adl;
        }

        private Dictionary<Guid, string> GetLookupTableDefinitionList(Guid lookupTableUid)
        {
            Dictionary<Guid, string> ltdl = new Dictionary<Guid, string>();
            foreach (KeyValuePair<Guid, LookupTableDefinitionList> kvp in _lookupTableDefList)
            {
                if (kvp.Value.LookupTableUid == lookupTableUid)
                {
                    ltdl.Add(kvp.Value.ValueUid, kvp.Value.Value);
                }
            }
            return ltdl;

        }

        private Guid GetLookupTableIdForCustomField(string customFieldName)
        {
            return GetLookupTableIdForCustomField((getCustomFieldGuid(customFieldName)));
        }

        private Guid GetLookupTableIdForCustomField(Guid customFieldUid)
        {
            return _customFieldsWithLookupTables[customFieldUid];
        }

        private bool CustomFieldHasLookupTable(string customFieldName)
        {
            return CustomFieldHasLookupTable((getCustomFieldGuid(customFieldName)));
        }

        private bool CustomFieldHasLookupTable(Guid customFieldUid)
        {
            foreach (KeyValuePair<Guid, Guid> kvp in _customFieldsWithLookupTables)
            {
                //if (kvp.Value == CustomFieldID)
                if (kvp.Key == customFieldUid)
                {
                    return true;
                }
            }
            return false;
        }

        private bool LookupMappingCorrect(FieldMapping mappedField)
        {
            // Determine if this is a Custom Field mapping
            if ((mappedField.PSField.CustomFieldUid) != Guid.Empty)
            {
                // Determine if field has lookup table
                if (CustomFieldHasLookupTable(mappedField.PSField.CustomFieldUid))
                {
                    // Custom Field has lookup table, make sure there are mappings.
                    if (mappedField.LookupMap == null)
                        return false;
                }
            }
            return true;
        }

        #endregion

        #region Button Events
        private void buttonSave_Click(object sender, EventArgs e)
        {
            bool lookupTableProblem = false;
            bool nullMappingExists = false;
            Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            Collection<FieldMapping> fields = new Collection<FieldMapping>();
            foreach (KeyValuePair<int, FieldMapping> kvp in _fieldMappings)
            {
                fields.Add(kvp.Value);
                if (!LookupMappingCorrect(kvp.Value))
                    lookupTableProblem = true;
                if ((kvp.Value.PSField.CustomFieldUid == Guid.Empty) && 
                    (String.IsNullOrEmpty(kvp.Value.PSField.BuiltInName)))
                    nullMappingExists = true;
            }

            Cursor.Current = System.Windows.Forms.Cursors.Default;

            if (lookupTableProblem || nullMappingExists)
            {
                string dialogString = String.Format(CultureInfo.InvariantCulture, Resources.QuestionFieldMappings, Resources.ButtonOK, Resources.ButtonCancel);
                if (lookupTableProblem)
                    dialogString = Resources.LookupTableMapMissing + dialogString;
                if (nullMappingExists)
                    dialogString = Resources.NullTableMapping + dialogString;
                DialogResult dr = RightAwareMessageBox.Show(dialogString, Resources.EditorTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    ptrMain.UpdateFieldMappings(fields);
                    this.Close();
                }
            }
            else
            {
                ptrMain.UpdateFieldMappings(fields);
                this.Close();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonAddToMapped_Click(object sender, EventArgs e)
        {
            if (listBoxAvailablePPSFields.SelectedItem != null)
            {
                int AttributeID = getAttributeID(listBoxAvailablePPSFields.SelectedItem.ToString());
                AddToMappingList(AttributeID);
                _fieldMappings.Add(AttributeID, new FieldMapping(AttributeID.ToString(CultureInfo.InvariantCulture), string.Empty, Guid.Empty));
            }
        }

        private void buttonRemoveFromMapped_Click(object sender, EventArgs e)
        {
            if (listBoxMappedPPSFields.SelectedItem != null)
            {
                int AttributeID = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());
                RemoveFromMappingList(AttributeID);
                _fieldMappings.Remove(AttributeID);
            }
        }

        private void buttonMapLookupValues_Click(object sender, EventArgs e)
        {
            if ((listBoxMappedPPSFields.SelectedIndex >= 0) && (comboBoxPSCustomField.Text.Length > 0))
            {
                Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                FormMapLookupValues mlv = new FormMapLookupValues(this);

                int attId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());
                if (mlv.SetLists(attId, GetAttributeDefinitionList(attId),
                    GetLookupTableDefinitionList(GetLookupTableIdForCustomField(comboBoxPSCustomField.Text)),
                    GetLookupMapTable(attId)))
                {
                    Cursor.Current = System.Windows.Forms.Cursors.Default;
                    mlv.ShowDialog(this);
                }
                else
                {
                    Cursor.Current = System.Windows.Forms.Cursors.Default;
                    RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ItemCountMismatch, listBoxMappedPPSFields.SelectedItem.ToString(), comboBoxPSCustomField.Text), Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                RightAwareMessageBox.Show(Resources.MapValueFirst, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #endregion

        #region Control Events

        private void listBoxMappedPPSFields_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxMappedPPSFields.SelectedItem != null)
            {
                // Enable the drop downs and radio buttons since there is a selection in listBoxMappedPPSFields
                ChangePSMappingControlsEnabled(true);
                int attributeId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());

                // Check if this is a new attribute added
                FieldMapping fm = _fieldMappings[attributeId];
                if ((fm.PSField.CustomFieldUid == Guid.Empty) &&
                    (String.IsNullOrEmpty(fm.PSField.BuiltInName)))
                {
                    // New attribute
                    radioButtonPSCustomField.PerformClick();
                    comboBoxPSBuiltInField.SelectedIndex = 0;
                    comboBoxPSCustomField.SelectedIndex = 0;
                }
                else
                {
                    // Existing attribute
                    if (fm.PSField.CustomFieldUid != Guid.Empty)
                    {
                        // Using a custom field
                        comboBoxPSCustomField.SelectedItem = _customFieldList[fm.PSField.CustomFieldUid];
                        radioButtonPSCustomField.PerformClick();
                    }
                    else
                    {
                        // using a built in field
                        comboBoxPSBuiltInField.SelectedItem = fm.PSField.BuiltInName;
                        comboBoxPSBuiltInField.SelectedIndex = 0;
                        comboBoxPSCustomField.SelectedIndex = 0;
                    }
                }
            }
            else
            {
                // Disable the drop downs and radio buttons till there is a selection in listBoxMappedPPSFields
                comboBoxPSBuiltInField.SelectedItem = "";
                ChangePSMappingControlsEnabled(false);
            }
        }

        private void radioButtonPSBuiltInField_Click(object sender, EventArgs e)
        {
            if (radioButtonPSBuiltInField.Checked)
            {
                comboBoxPSBuiltInField.Enabled = true;
                comboBoxPSCustomField.Enabled = false;
                int attributeId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());

                _fieldMappings[attributeId].PSField.CustomFieldUid = Guid.Empty;
                _fieldMappings[attributeId].PSField.BuiltInName = comboBoxPSBuiltInField.Text;
            }
        }

        private void radioButtonPSCustomField_Click(object sender, EventArgs e)
        {
            if (radioButtonPSCustomField.Checked)
            {
                comboBoxPSBuiltInField.Enabled = false;
                comboBoxPSCustomField.Enabled = true;

                int attributeId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());

                _fieldMappings[attributeId].PSField.CustomFieldUid = getCustomFieldGuid(comboBoxPSCustomField.Text);
                _fieldMappings[attributeId].PSField.BuiltInName = string.Empty;
            }
        }

        private void comboBoxPSBuiltInField_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxMappedPPSFields.SelectedItem != null)
            {
                int attributeId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());

                _fieldMappings[attributeId].PSField.CustomFieldUid = Guid.Empty;
                _fieldMappings[attributeId].PSField.BuiltInName = comboBoxPSBuiltInField.Text;
            }
        }

        private void comboBoxPSCustomField_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxMappedPPSFields.SelectedItem != null)
            {
                int attributeId = getAttributeID(listBoxMappedPPSFields.SelectedItem.ToString());

                _fieldMappings[attributeId].PSField.CustomFieldUid = getCustomFieldGuid(comboBoxPSCustomField.Text);
                _fieldMappings[attributeId].PSField.BuiltInName = string.Empty;

                if (CustomFieldHasLookupTable(comboBoxPSCustomField.Text))
                    buttonMapLookupValues.Enabled = true;
                else
                    buttonMapLookupValues.Enabled = false;
            }
        }

        private void ChangePSMappingControlsEnabled(bool Enabled)
        {
            comboBoxPSBuiltInField.Enabled = Enabled;
            comboBoxPSCustomField.Enabled = Enabled;
            radioButtonPSBuiltInField.Enabled = Enabled;
            radioButtonPSCustomField.Enabled = Enabled;
        }
        #endregion

    }



}